from django.shortcuts import render

import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.utils_member import get_memberlevel

from api.models import Package
from api.serializers import PackageSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action
from api.mylogger import logger


# Create your views here.


class PackageViewSet(viewsets.ModelViewSet):
    table_name = Package._meta.db_table
    serializer_class = PackageSerializer
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name',  'desc', 'benefit', 'order', 'status'],
                                  properties={
                                      "name": openapi.Schema(type=openapi.TYPE_STRING, description="服务包名称"),
                                      "desc": openapi.Schema(type=openapi.TYPE_STRING, description="服务包描述"),
                                      "benefit": openapi.Schema(type=openapi.TYPE_STRING, description="服务包受益描述"),
                                      "order": openapi.Schema(type=openapi.TYPE_INTEGER, description="顺序号"),
                                      "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                  }, )

    @swagger_auto_schema(operation_id='添加服务包', tags=['package'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def package_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = PackageSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增服务包成功")
        return JsonResponse(serializer.errors, status=400)

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['id', 'name', 'desc', 'benefit', 'order', 'status'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部id"),
                                          "name": openapi.Schema(type=openapi.TYPE_STRING, description="服务包名称"),
                                          "desc": openapi.Schema(type=openapi.TYPE_STRING, description="服务包描述"),
                                          "benefit": openapi.Schema(type=openapi.TYPE_STRING, description="服务包受益描述"),
                                          "order": openapi.Schema(type=openapi.TYPE_INTEGER, description="顺序号"),
                                          "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                      }, )

    @swagger_auto_schema(operation_id='修改服务包', tags=['package'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def package_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        logger.debug(f"db id is {db_id}")
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")

        serializer = PackageSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=Package.objects.get(id=db_id), validated_data=data)
                logger.debug(f"db_res {db_ret}")
                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改服务包成功!")
            except ObjectDoesNotExist:
                logger.debug("没有修改记录")
                return failed_response_with_data(msg=self.table_name + f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除服务包', tags=['package'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="服务包的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def package_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        logger.debug(f"material id is {db_id}")
        # qry = Material.objects.filter(id=db_id)
        # print(qry.query)
        deleted_cnt, _ = Package.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "id": db_id,
            "rows_deleted": deleted_cnt,
            "info": "删除" + str(deleted_cnt) + "条记录!",
        }
        return success_response_with_data(res_data, msg="删除服务包记录成功!")

    @swagger_auto_schema(operation_id='单个服务包信息', tags=['package'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="服务包的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def package_one(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        logger.debug(f"package id is {db_id}")
        try:
            qry = Package.objects.get(id=db_id)
            logger.debug(f"material query one {qry}")
            serializer = PackageSerializer(qry)
            return success_response_with_data(serializer.data, msg="查询服务包成功!")
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的横幅!")

    @swagger_auto_schema(operation_id='服务包列表查询', tags=['package'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="服务包名称的部分信息"),
                             },
                         )
                         )
    @swagger_auto_schema(operation_id='服务包列表查询GET', tags=['package'],
                         method='GET',
                         manual_parameters=[
                             openapi.Parameter(name='query', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING,
                                               description='服务包名称的部分信息')
                         ]
                         )
    @action(methods=['POST', 'GET'], detail=False)
    def package_list(self, request):
        if request.method == 'POST':
            data = json.loads(request.body.decode('utf8'))
            current_page = data.get("pagenum", 1)
            page_size = data.get("pagesize", 10)
            query = data.get("query", '')

        if request.method == 'GET':
            current_page = request.GET.get("pagenum", 1)
            page_size = request.GET.get("pagesize", 10)
            query = request.GET.get("query", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = Package.objects
            if len(query):
                objects = objects.filter(name__icontains=query)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        package_list = PackageSerializer(rows, many=True).data
        for index in range(len(package_list)):
            row = package_list[index]
            from_level_code = row["from_level_code"]
            row["fromlevel"] = get_memberlevel(from_level_code)
            to_level_code = row["to_level_code"]
            row["tolevel"] = get_memberlevel(to_level_code)

        print("serializer.data", package_list)
        return list_response(package_list, total, page_size, current_page, self.table_name)

        # serializer = PackageSerializer(rows, many=True)
        # return list_response(serializer.data, total, page_size, current_page, self.table_name)



